package com.abner.basis.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 基于lock实现售票功能
 *      一共有30张票,3个售票员去卖,买完为止
 * @Author yuhui
 * @Date: 2024/3/19
 */
public class SaleTicket {
    public static void main(String[] args) {
        Ticket ticket = new Ticket();

        new Thread(() -> {
            for (int i = 0; i < 35; i++) {
                ticket.sale();
            }
        },"小明").start();

        new Thread(() -> {
            for (int i = 0; i < 35; i++) {
                ticket.sale();
            }
        },"小红").start();

        new Thread(() -> {
            for (int i = 0; i < 35; i++) {
                ticket.sale();
            }
        },"小刚").start();
    }
}


class Ticket {
    /**
     * 票数
     */
    private int num = 30;

    /**
     * 可重入锁
     */
    private final Lock lock = new ReentrantLock();


    /**
     * 卖票
     */
    public  void sale() {
        try {
            lock.lock();
            if(num > 0) {
                System.out.println(Thread.currentThread().getName()+"卖出了1张票,还剩"+ (num--  -1) + "张票");
            }
        }finally {
            lock.unlock();
        }
    }
}